<template>
  <div class="major-search-main">
    <div class="main-wrapper">
      <MajorSearch
        ref="majorSearchRef"
        @majorSearch="handleMajorSearch"
        @majorSelect="handleSelectMajor"
      ></MajorSearch>
      <div class="industry-list scroll-list" @scroll="handleScroll">
        <template v-for="item in showIndustryData" :key="item.id">
          <IndustryItem :item="item"></IndustryItem>
        </template>
        <van-loading
          v-if="loading && !finished"
          type="spinner"
          color="#0b6eff"
          size="36px"
        />
        <div
          class="empty-container"
          v-if="!showIndustryData.length && finished"
        >
          <NotData :text="'暂无相关产业'" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onActivated } from 'vue';
import { getIndustryTreeReq } from '@/api/industryMap.js';
import IndustryItem from '@/views/industryMap/industryHome/components/IndustryItem.vue';
import MajorSearch from '@/views/industryMap/industryHome/components/MajorSearch.vue';
import NotData from '@/views/industryMap/components/NotData.vue';

import antiShake from '@/utils/antiShake.js'; // 引入防抖函数

const industryList = ref([]);

const showIndustryData = ref([]);
const pageNum = ref(1);
const pageSize = ref(12);
const finished = ref(false);
const loading = ref(false);
const majorIds = ref('');


const handleMajorSearch = (val) => {
  majorIds.value =
    Array.isArray(val) && val.map((item) => item.positionTagId).join(',');
  getIndustryTree();
};
const handleSelectMajor = (val) => {
  majorIds.value = val.join(',');
  getIndustryTree();
};

const getIndustryTree = async () => {
  loading.value = true;
  reset();
  const params = {
    industryType: 10,
    extend: majorIds.value,
  };
  const res = await getIndustryTreeReq(params);
  let data = JSON.parse(JSON.stringify(res.data)) || [];
  // 暂时只需要战略新兴产业+国标行业
  data = data.filter((item) => item.id == 5 || item.id == 2107);
  industryList.value = flattenIndustryData(data);
  finished.value = false;
  handleSliceData();
  loading.value = false;
};
// 数据扁平化
const flattenIndustryData = (data) => {
  return data.flatMap((topItem) =>
    topItem.child.flatMap((secondItem) => [
      // 第二层级（保留所有字段）
      { ...secondItem },
      // 第三层级（保留所有字段）
      ...(secondItem.child?.map((thirdItem) => ({
        ...thirdItem,
      })) || []),
    ])
  );
};
const handleScroll = antiShake(() => {
  const listElement = document.querySelector('.scroll-list');
  if (listElement) {
    const { scrollTop, scrollHeight, clientHeight } = listElement;
    if (scrollTop + clientHeight >= scrollHeight - 10 && !finished.value) {
      handleSliceData();
    }
  }
}, 300);
const handleSliceData = () => {
  loading.value = true;
  showIndustryData.value = showIndustryData.value.concat(
    industryList.value.slice(
      (pageNum.value - 1) * pageSize.value,
      pageNum.value * pageSize.value
    )
  );
  pageNum.value++;
  if (showIndustryData.value.length >= industryList.value.length) {
    finished.value = true;
  }
  loading.value = false;
};
const reset = () => {
  pageNum.value = 1;
  showIndustryData.value = [];
  industryList.value = [];
  finished.value = false;
};
onActivated(() => {
  reset();
  getIndustryTree();
});
</script>
<style lang="scss" scoped>
.major-search-main {
  height: 100%;
  padding: 0 60px 32px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  .main-wrapper {
    width: 100%;
    height: 100%;
    padding: 16px 0 32px 32px;
    background: #eff9ff;
    border-radius: 38px;
    display: flex;
    flex-direction: row;
    box-sizing: border-box;
  }
}

.industry-list {
  flex: 1;
  height: 100%;
  padding: 16px 32px;
  overflow: hidden;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 196px 196px 196px;
  grid-gap: 32px 22px;
  box-sizing: border-box;
  .industry-item {
    height: 196px;
  }
}
.van-loading {
  grid-column-start: span 3;
  text-align: center;
}
.empty-container {
  grid-column-start: span 3;
  grid-row-start: span 3;
}
</style>
